using Godot;

namespace RoboRampage.Player;

public partial class WeaponHandler : Node3D
{
    [Export] public Node3D ExWeaponMesh1;
    [Export] public Node3D ExWeaponMesh2;
    public override void _Ready()
    {
        Equip(ExWeaponMesh1);
    }

    /**
 * 输入事件监听
 */
    public override void _UnhandledInput(InputEvent @event)
    {
        if (@event.IsActionPressed("weapon_1"))
            Equip(ExWeaponMesh1);

        if (@event.IsActionPressed("weapon_2"))
            Equip(ExWeaponMesh2);

        if (@event.IsActionPressed("next_weapon"))
            NextWeapon();
        if (@event.IsActionPressed("last_weapon"))
            LastWeapon();
    }

    public void Equip(Node3D activeWeapon)
    {
        // 获取当前节点的所有子节点
        for (int i = 0; i < GetChildren().Count; i++)
        {
            // 将每个子节点转换为Node3D类型
            HitscanWeapon child = (HitscanWeapon)GetChildren()[i];
            // 如果子节点是活动武器，则设置为可见，否则设置为不可见
            child.Visible = child == activeWeapon;
            // 如果子节点是活动武器，则启用其处理过程，否则禁用
            child.SetProcess(child == activeWeapon);
            // 如果子节点是活动武器,更新活动武器的弹药标签
            if (child == activeWeapon)
                child.ExAmmonHandler.UpdateAmmoLabel(child.ExEnumTypeAmmo);
        }
    }

    private void NextWeapon()
    {
        // 获取当前武器的索引
        var index = GetCurrentIndex();
        index = Mathf.Wrap(index + 1, 0, GetChildCount());
        Equip((Node3D)GetChild(index));
    }

    private void LastWeapon()
    {
        // 获取当前武器的索引
        var index = GetCurrentIndex();
        index = Mathf.Wrap(index - 1, 0, GetChildCount());
        Equip((Node3D)GetChild(index));
    }

    private int GetCurrentIndex()
    {
        for (int i = 0; i < GetChildCount(); i++)
        {
            if (GetChild(i) is Node3D { Visible: true })
            {
                return i;
            }
        }

        return -1;
    }
}